package service

import (
	"CDSystem/v2/config"
	"CDSystem/v2/dao"
	"CDSystem/v2/model"
	"encoding/json"
	"errors"
	"log"
)

func PostToApi(pps model.PostParams) (model.ClientResponse, error) {
	cRes := model.ClientResponse{}
	var err error
	defer func() {
		if err != nil {
			cRes.Err = err.Error()
		}
	}()
	//查询数据库,获取推理标签
	label, image, err := dao.GetLabelAndImage(pps.Image)
	if err != nil {
		log.Println("未找到标签")
		return cRes, err
	}
	//调用后处理API
	log.Println("调用后处理Api")
	log.Println(pps.Task, pps.Postfunc, pps.Param)
	pr := model.PostRequest{
		Task:     pps.Task,
		Label:    label,
		Image:    image,
		Postfunc: pps.Postfunc,
		Param:    pps.Param,
	}
	prJson, err := json.Marshal(&pr)
	if err != nil {
		return cRes, err
	}
	rspBody, err := sendPost(prJson, config.Cfg.System.InferApiUrl+"/api/postprocess")
	if err != nil {
		return cRes, err
	}
	var res model.PostResponse
	if err = json.Unmarshal(rspBody, &res); err != nil {
		return cRes, err
	}
	if res.Code != 200 {
		err = errors.New(res.Err)
		return cRes, err
	}
	cRes.Image = pps.Image
	cRes.Code = res.Code
	cRes.Prod = res.Prod
	cRes.Time = res.Time
	return cRes, err
}
